﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using W.Device.Domain.DTO;
using W.Purchase.Read.API.AppLication.Command.Command;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace W.Purchase.Read.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UnitController : ControllerBase
    {
        private readonly IMediator mediator;
        public UnitController(IMediator mediator)
        {
            this.mediator = mediator;
        }
        /// <summary>
        /// 显示单位信息
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<PageDTO<Domain.Unit>>> Handle([FromQuery] UnitShowCommand command)
        {
            ApiResult<PageDTO<Domain.Unit>> list = new ApiResult<PageDTO<Domain.Unit>>();
            try
            {
                list.Data = await mediator.Send(command);
            }
            catch (Exception ex)
            {
                list.Code = -1;
                list.Message = ex.Message;
                throw;
            }
            return list;
        }
        /// <summary>
        /// 导出产品类别管理
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ProductTypeExcel([FromQuery] UnitShowCommand command)
        {
            var list = await mediator.Send(command);

            IWorkbook book = new XSSFWorkbook();
            ISheet sheet = book.CreateSheet("产品类别管理");

            IRow rowl = sheet.CreateRow(0);
            rowl.CreateCell(0).SetCellValue("单位编号");
            rowl.CreateCell(1).SetCellValue("单位名称");
            rowl.CreateCell(2).SetCellValue("备注");


            int index = 1;
            foreach (var item in list.List)
            {
                rowl = sheet.CreateRow(index);
                rowl.CreateCell(0).SetCellValue(item.UnitNo);
                rowl.CreateCell(1).SetCellValue(item.UnitName);
                rowl.CreateCell(2).SetCellValue(item.UnitRemarks);

                index++;
            }
            byte[] bytes;

            using (MemoryStream ms = new MemoryStream())
            {
                book.Write(ms);
                bytes = ms.ToArray();
            }
            string mapPath = new FileExtensionContentTypeProvider().Mappings[".xlsx"];
            return File(bytes, mapPath, "产品类别管理信息.xlsx");
        }
    }
}
